#pragma once
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <cstring>
#include "log.hpp"
#include"Init.hpp"

extern Log lg;
Init init;

class Task
{
public:
    Task(int fd, const uint16_t &port, const std::string &ip)
        : sockfd(fd), clientport(port), clientip(ip)
    {
    }

    Task()
    {
    }
    void Run() // 这里不是循环 发一次数据就结束了哈 是把
    {
         while (true)
         {
            char buffer[4096];
            // std::cout << "Client say# " << std::endl;
            int n = read(sockfd, buffer, sizeof(buffer));
            // std::cout << n << std::endl;
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "client say# " << buffer << std::endl;
                std::string echo_string = "server echo# ";
                echo_string += init.translation(buffer);
                
                n = write(sockfd, echo_string.c_str(), echo_string.size());
                if (n < 0)
                {
                    lg(Warning, "write error, errno : %d, errstring: %s", errno, strerror(errno));
                }
            }
            else if (n == 0)
            {
                lg(Info, "%s:%d quit,server close sockfd:%d", clientip.c_str(), clientport, sockfd);
                break;
            }
            else
            {
                lg(Warning, "read error,sockfd:%d,client ip:%s,client port:%d", sockfd, clientip.c_str(), clientport);
                break;
            }
         }        
        close(sockfd);

        
    }

    void operator()() // t() 调用这个函数你的主线程在while里面  这里只创建的线程执行的逻辑 创建的线程在执行任务呀 这里就是你的任务哈
    {
        Run();
    }
    ~Task()
    {
    }

private:
    int sockfd;
    uint16_t clientport;
    std::string clientip;
};